#! /bin/sh
### BEGIN INIT INFO
# Provides:
# Required-Start:
# Required-Stop:
# Default-Start:
# Default-Stop:
# Short-Description: Starts and stops the iSCSI initiator services and logins to default targets
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/sbin/iscsid
ADM=/sbin/iscsiadm
PIDFILE=/run/iscsid.pid

[ -x "$DAEMON" ] || exit 0

. /lib/lsb/init-functions

if [ ! -d /sys/class/ ]; then
  log_failure_msg "iSCSI requires a mounted sysfs, not started."
  exit 1
fi

nodestartup_re='s/^node\.conn\[0]\.startup[ 	]*=[ 	]*//p'

RETVAL=0

start() {
	log_daemon_msg "Starting iSCSI initiator service" "iscsid"
	modprobe -q iscsi_tcp 2>/dev/null || :
	modprobe -q ib_iser 2>/dev/null || :
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON
	RETVAL=$?
	log_end_msg $RETVAL
	starttargets
}

starttargets() {
	log_daemon_msg "Setting up iSCSI targets"
	$ADM -m node --loginall=automatic
	log_end_msg 0
}

stoptargets() {
	log_daemon_msg "Disconnecting iSCSI targets"
	sync
	$ADM -m node --logoutall=all
	RETVAL=$?
	log_end_msg $RETVAL
}

stop() {
	stoptargets
	if [ $RETVAL -ne 0 ]; then
		log_failure_msg "Could not stop all targets, try again later"
		return $RETVAL
	fi

	log_daemon_msg "Stopping iSCSI initiator service"
	start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON
	rm -f $PIDFILE
	status=0
	modprobe -r ib_iser 2>/dev/null
	if [ "$?" -ne "0" -a "$?" -ne "1" ]; then
		status=1
	fi
	modprobe -r iscsi_tcp 2>/dev/null
	if [ "$?" -ne "0" -a "$?" -ne "1" ]; then
		status=1
	fi
	log_end_msg $status
}

restart() {
	stop
	if [ $RETVAL -ne 0 ]; then
		log_failure_msg "Stopping iSCSI initiator service failed, not starting"
		return $RETVAL
	fi
	start
}

restarttargets() {
	stoptargets
	if [ $RETVAL -ne 0 ]; then
		log_failure_msg "Could not stop all targets, try again later"
		return $RETVAL
	fi
	starttargets
}

status() {
	#XXX FIXME: what to do here?
	#status iscsid
	# list active sessions
	echo Current active iSCSI sessions:
	$ADM -m session
}

case "$1" in
	start|starttargets|stop|stoptargets|restart|restarttargets|status)
		$1
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
		;;
esac
exit $RETVAL
